import {AvatarDropdown, AvatarName, Footer, OrgInfo/*, Question*/} from '@/components';
import type {Settings as LayoutSettings} from '@ant-design/pro-components';
import {SettingDrawer} from '@ant-design/pro-components';
import type {RequestConfig, RunTimeLayoutConfig} from '@umijs/max';
import {history, Link} from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import {errorConfig} from './requestErrorConfig';
import {currentUser as queryCurrentUser} from './services/ant-design-pro/api';

const loginPath = '/user/login';
const isDev = process.env.NODE_ENV === 'development';
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
    settings?: Partial<LayoutSettings>;
    currentUser?: API.CurrentUser;
    loading?: boolean;
    fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
    const fetchUserInfo = async () => {
        try {
            const msg = await queryCurrentUser({
                skipErrorHandler: true,
            });
            return msg.data;
        } catch (error) {
            // history.push(loginPath);
            history.push('/bigScreen');
        }
        return undefined;
    };
    // 如果不是登录页面，执行
    const {location} = history;
    if (![loginPath, '/user/register', '/user/register-result','/bigScreen'].includes(location.pathname)) {
        const currentUser = await fetchUserInfo();
        return {
            fetchUserInfo,
            currentUser,
            settings: defaultSettings as Partial<LayoutSettings>,
        };
    }
    return {
        fetchUserInfo,
        settings: defaultSettings as Partial<LayoutSettings>,
    };
}


// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {
    return {
        headerContentRender: () => [<OrgInfo key="orginfo" />],
        // actionsRender: () => [],
        avatarProps: {
            // src: initialState?.currentUser?.avatar,
            title: <AvatarName/>,
            render: (_, avatarChildren) => {
                return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
            },
        },
        waterMarkProps: {
            content: initialState?.currentUser?.account,
        },
        // rightRender: () =>  <OrgInfo key="orginfo" />,
        // footerRender: () => <Footer />,
        // breadcrumbRender:  () => {false},
        onPageChange: () => {
            const {location} = history;
            // 如果没有登录，重定向到 login
            // if (!initialState?.currentUser && location.pathname !== loginPath) {
            //     history.push(loginPath);
            // }
        },
        bgLayoutImgList: [],
        // links: isDev
        //   ? [
        //       <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
        //         <LinkOutlined />
        //         <span>OpenAPI 文档</span>
        //       </Link>,
        //     ]
        //   : [],
        menuHeaderRender: undefined,
        // 自定义 403 页面
        // unAccessible: <div>unAccessible</div>,
        // 增加一个 loading 的状态
        childrenRender: (children) => {
            // if (initialState?.loading) return <PageLoading />;
            return (
                <>
                    {children}
                    {isDev && (
                        <SettingDrawer
                            disableUrlParams
                            enableDarkTheme
                            settings={initialState?.settings}
                            onSettingChange={(settings) => {
                                setInitialState((preInitialState) => ({
                                    ...preInitialState,
                                    settings,
                                }));
                            }}
                        />
                    )}
                </>
            );
        },
        token: {
            bgLayout: '#F4F8FE',
            sider: {
                colorMenuBackground: '#fff',
                colorBgMenuItemCollapsedSelected: 'transparent',
                colorBgMenuItemCollapsedElevated: '#fff',
                colorBgMenuItemCollapsedHover: 'rgb(241,246,255)',
                colorBgMenuItemSelected: 'rgb(241,246,255)',
                colorBgMenuItemHover: 'rgb(241,246,255)',
                colorTextMenuSelected: 'rgb(0, 97, 232)',
                colorTextMenuItemHover: 'rgb(0, 97, 232)',
                colorTextMenu: 'rgb(51,51,51)',
                colorTextMenuActive: 'rgb(0, 97, 232)',
            },
            pageContainer: {
                paddingInlinePageContainerContent: 24,
                paddingBlockPageContainerContent: 0,
            },
            header: {
                heightLayoutHeader: 64,
                colorTextRightActionsItem: 'rgb(0, 0, 0)',
                colorBgHeader: '#fff',
                colorHeaderTitle: 'rgba(51,51,51)',
            },
        },
        ...initialState?.settings,
    };
};

function setToken(token: string) {
    localStorage.setItem('jwt', token);
}

function getToken(): string {
    return localStorage.getItem('jwt') || '';
}

const authHeaderInterceptor = (url: string, options: RequestConfig) => {
    var token = getToken()
    // const authHeader = { Authorization: 'Bearer ' + token };
    const authHeader = {'x-token': token};
    return {
        url: `${url}`,
        options: {...options, interceptors: true, headers: authHeader},
    };
};

const authResponseInterceptors = (response: Response, options: RequestConfig) => {
    var token = response.headers.get('x-refresh-token') || ''
    if (token !== '') {
        setToken(token);
    }
    return response;
};

const demoResponseInterceptors = (response: Response, options: RequestConfig) => {
    response.headers.append('interceptors', 'yes yo');
    return response;
};

// @ts-ignore
/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */


export const request: RequestConfig = {
    //baseURL: 'https://proapi.azurewebsites.net',
    baseURL: API_SERVER.default,
    ...errorConfig,

    // 请求前拦截器
    requestInterceptors: [authHeaderInterceptor],

    // 请求后拦截器
    // responseInterceptors: [authResponseInterceptors],
};
